package cn.innosmart.aq.view.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.BoxBean;
import cn.innosmart.aq.bean.Contact;
import cn.innosmart.aq.manager.ContactsManager;
import cn.innosmart.aq.util.AppUtil;
import cn.innosmart.aq.util.INetworkInteractUtil;
import cn.innosmart.aq.util.NetworkInteractUtil;
import cn.innosmart.aq.util.NetworkTool;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2015/6/12.
 */
public class SplashActivity extends BaseActivity implements INetworkInteractUtil {
    private static final long SHOW_TIME_MIN = 2000;
    //Splash界面维持时间设定
    private long startTime;
    //加载时间
    private long loadingTime;
    private NetworkInteractUtil interactUtil;
    //版本号显示
    private TextView tvVersion;
    //网络检测
    private TextView tvNetworkDetectProgress;

    private Handler mHander = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    //跳到盒子列表界面
                    jumpFishList();
//                    jumpBoxList();
                    break;
                case 1:
                    //直接跳到鱼缸列表界面
                    BoxBean boxBean = (BoxBean) msg.obj;
                    jumpAquarium(boxBean);
                    break;
                case 0xFF: {
                    int count = msg.arg1;
                    if (tvNetworkDetectProgress != null)
                        tvNetworkDetectProgress.setText(getResources().getString(R.string.network_check) + " " + count);
                    break;
                }
            }
        }
    };
    public static String lang;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        //设置版本号信息
        tvVersion = (TextView) findViewById(R.id.tv_version);
        tvVersion.setText(AppUtil.getInstance().getVersion(this, 0));
        //显示的起始界面
        startTime = System.currentTimeMillis();
        lang = Locale.getDefault().toString();

        add_service_phone();
        show_network_check_progress();

        //网络交互数据初始化
        interactUtil = new NetworkInteractUtil(this);
        if (checkNetWork()) {
            //获取Banner信息
            interactUtil.getBanner();
            //获取账号信息
            getCountInfo();
        } else {
            //网络连接故障
            showToast(getString(R.string.network_error));
            //检查账号信息
            checkUserInfo();
            //因为网络问题，手动调用网络交互结束接口
            onNetworkInteractAllOver(0);
        }
    }

    private Uri SMS_INBOX = Uri.parse("content://sms/");

    public String getSmsFromPhone() {
        ContentResolver cr = getContentResolver();
        String[] projection = new String[]{"address", "body"};//"_id", "addrss", "person",, "date", "type
        String where = "date >  "
                + (System.currentTimeMillis() - 24 * 60 * 60 * 1000);
        Cursor cur = cr.query(SMS_INBOX, projection, null, null, "date desc");
        if (null == cur)
            return null;
        if (cur.moveToFirst()) {
            String number = cur.getString(cur.getColumnIndex("address"));//手机号
            //String name = cur.getString(cur.getColumnIndex("person"));//联系人姓名列表
            String body = cur.getString(cur.getColumnIndex("body"));
            System.out.println("sms body: " + body);
            if (body.contains("缸缸好")) {
                return number;
            }
        }

        return null;
    }

    private String detectSMSServiceNo() {
        return getSmsFromPhone();
    }

    private void add_service_phone() {
        ContactsManager cm = new ContactsManager(this.getContentResolver());

        if (cm == null)
            return;

        String nameTel;
        String nameSMS;
        String telno;
        String smsno;

        if (lang.equals("zh_TW")) {
            nameTel = "缸缸好客服電話";
            nameSMS = "缸缸好客服簡訊";
            telno = "051085220302";
            smsno = "10690576934719687";

        } else if (lang.equals("zh_CN")) {
            nameTel = "缸缸好客服电话";
            nameSMS = "缸缸好客服短信";
            telno = "051085220302";
            smsno = "10690576934719687";

        } else {
            nameTel = "Dr.AQ Service Call";
            nameSMS = "Dr.AQ Service SMS";
            telno = "051085220302";
            smsno = "10690576934719687";
        }

        String foundSMSNumber = detectSMSServiceNo();
        if (foundSMSNumber != null) {
            smsno = foundSMSNumber;
            System.out.println("Correct No:" + smsno);

        }


        if (cm.searchContact(nameTel).getId().equals("0")) {
            Contact contactTel = new Contact();
            contactTel.setName(nameTel);
            contactTel.setNumber(telno);
            contactTel.setEmail("");
            cm.addContact(contactTel);

            Contact contactSMS = new Contact();
            contactSMS.setName(nameSMS);
            contactSMS.setNumber(smsno);
            contactSMS.setEmail("");
            cm.addContact(contactSMS);
        }
    }

    private void show_network_check_progress() {
        tvNetworkDetectProgress = (TextView) findViewById(R.id.tv_network_check_progress);

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int count = 20; count > 0; count--) {
                    Message msg = new Message();
                    msg.what = 0xFF;
                    msg.arg1 = count;
                    if (mHander != null)
                        mHander.sendMessage(msg);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        t.start();
    }

    /**
     * 检查用户信息（盒子列表）
     */
    private void checkUserInfo() {
        JSONObject loginJson = SharedUtil.getInstance().readLoginInfo();
        String username = null;
        String password = null;
        try {
            username = loginJson.getString("username");
            password = loginJson.getString("password");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String gatewayInfo = SharedUtil.getInstance().readLocalGatewayInfo();
        if (username == null || password == null) {
            SystemConstant.boxBeanList = new ArrayList<>();
        } else {
            if (gatewayInfo != null)
//                SystemConstant.boxBeanList = GatewayListUtil.getInstance().analyseGatewayInfo(gatewayInfo);
                SystemConstant.boxBeanList = (ArrayList<BoxBean>) JSON.parseArray(gatewayInfo, BoxBean.class);
            else
                SystemConstant.boxBeanList = new ArrayList<>();
        }
    }

    /**
     * 获取账号信息
     */
    private void getCountInfo() {
//        SharedPreferences loginSp = getSharedPreferences(SystemConstant.Count, MODE_PRIVATE);
        SharedPreferences gatwayInfoSp = getSharedPreferences(SystemConstant.Project, MODE_PRIVATE);
        JSONObject loginSp = SharedUtil.getInstance().readLoginInfo();
        String username = null;
        String password = null;
        try {
            username = loginSp.getString("username");
            password = loginSp.getString("password");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //初始化BoxBeanList
        SystemConstant.boxBeanList = new ArrayList<BoxBean>();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            //手机号密码不存在，说明没有账户信息，则不调用gateway列表(要清掉上次缓存的数据)
//            gatwayInfoSp.edit().remove("boxlistinfo").commit();
//            interactUtil.getBanner();
        } else {
            //手机号密码存在，调用s获取该手机号gateway列表
            interactUtil.login(username, password, true);
        }
        interactUtil.checkFlags();
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 直接进入Box列表界面
     */
    private void jumpBoxList() {
        Intent intent = new Intent(SplashActivity.this, BoxListActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    private void jumpFishList() {
        Intent intent = new Intent(SplashActivity.this, FishListActivity.class);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 直接进入到鱼缸界面
     *
     * @param boxBean
     */
    private void jumpAquarium(BoxBean boxBean) {
        Intent intent = new Intent(SplashActivity.this, BoxDetailActivity.class);
        intent.putExtra("BoxBean", boxBean);
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
    }

    /**
     * 检查网络状况
     * true已连接 false未连接
     *
     * @return
     */
    private boolean checkNetWork() {
        return NetworkTool.getInstance().isOpenNetwork(SplashActivity.this);
    }

    /**
     * @param ret
     */
    @Override
    public void onNetworkInteractAllOver(int ret) {
        if (ret == -1) {
            showToast(SplashActivity.this.getString(R.string.network_error));
            checkUserInfo();
        }
        loadingTime = System.currentTimeMillis() - startTime;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (loadingTime < SHOW_TIME_MIN) {
                    System.out.println("loadingTime=" + loadingTime);
                    try {
                        Thread.sleep(SHOW_TIME_MIN - loadingTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                String lastDid = SharedUtil.getInstance().readLastConnect();
                if (SystemConstant.loginStatus == SystemConstant.Online) {
                    if (lastDid == null) {
                        mHander.sendEmptyMessage(0); //enter gateway list ui
                    } else {
                        Message msg = mHander.obtainMessage();
                        BoxBean boxBean = null;
                        for (int i = 0; i < SystemConstant.boxBeanList.size(); i++) {
                            if (lastDid.equals(SystemConstant.boxBeanList.get(i).getUid())) {
                                boxBean = SystemConstant.boxBeanList.get(i);
                                break;
                            }
                        }
                        if (boxBean == null) {
                            mHander.sendEmptyMessage(0);
                        } else {
                            if (SystemConstant.boxBeanList.size() == 1) {
                                msg.obj = boxBean;
                                msg.what = 1;
                                mHander.sendMessage(msg);
                            } else {
                                mHander.sendEmptyMessage(0);
                            }
                        }
                    }
                } else {
                    mHander.sendEmptyMessage(0);
                }

            }
        }).start();
    }

    @Override
    public void onNetworkInteractOver(int ret, String flag, Object object) {
    }

    @Override
    public void onBackPressed() {
    }
}
